<template>
  <div>
    <div align="right">
      <a-button
        type="primary"
        status="warning"
        @click="nextStep('5')"
        size="small"
        >上一步</a-button
      >
    </div>
    <a-form ref="accountInfoFromRef" :model="mainForm">
      <a-form-item label="补充材料">
        <div>
          <a-upload
            list-type="picture-card"
            :headers="{ token: accessToken }"
            :action="uploadFile"
            :style="{ marginRight: '10px' }"
            :on-error="handleError"
            :limit="5"
            :file-list="picArr"
            @before-upload="beforeUpload"
            @before-remove="picArrBeforeRemove"
            image-preview
          >
          </a-upload>
          <a-button
            type="primary"
            @click="handleClickImg('business_addition_pics')"
            >上传图片</a-button
          >
        </div>
        <template #extra><div>最多可上传五张照片</div></template>
      </a-form-item>
      <a-form-item label="特殊资质图片">
        <div>
          <a-upload
            list-type="picture-card"
            :headers="{ token: accessToken }"
            :action="uploadFile"
            :style="{ marginRight: '10px' }"
            :on-error="handleError"
            :limit="5"
            :file-list="otherPicArr"
            @before-upload="beforeUpload"
            @before-remove="otherPicArrBeforeRemove"
            image-preview
          >
          </a-upload>
          <a-button type="primary" @click="handleClickImg('qualifications')"
            >上传图片</a-button
          >
        </div>
        <template #extra>
          <div>
            <p
              >1、根据所属行业的特殊资质要求提供，详情查看<a-link
                @click="rateSettlementRules()"
                :hoverable="false"
                style="font-size: 12px"
                >费率结算规则对照表</a-link
              >。</p
            >
            <p
              >2、最多可上传5张照片，请填写通过图片上传API接口预先上传图片生成好的MediaID</p
            >
          </div>
        </template>
      </a-form-item>
      <a-form-item label="补充说明">
        <a-textarea
          allow-clear
          style="width: 700px"
          :max-length="512"
          show-word-limit
          v-model="mainForm.business_addition_desc"
        />
      </a-form-item>
    </a-form>

    <a-modal
      v-model:visible="showOssManager"
      :width="1100"
      @ok="handleOss"
      title="oss资源管理"
      @cancel="showOssManager = false"
    >
      <ossManages
        :initialize="showOssManager"
        @selected="changOssImage"
        :isSingle="true"
      ></ossManages>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, watch, computed, ref } from 'vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { useAppStore } from '@/store';
  import {
    getBankInfo,
    getPersonalBankInfo,
    getProvinces,
    getBranches,
  } from '@/api/shops';
  import store from '@/utils/storage';
  import { Message } from '@arco-design/web-vue';
  import uploadFile from '@/api/index';
  import ossManages from '@/components/oss-manage/index.vue';

  const fileFormat = ref<Array<string>>(['jpg', 'jpeg', 'png', 'gif', 'bmp']);
  // 携带toekn
  const accessToken = ref<string>(store.getAccessToken() || '');
  const appStore = useAppStore();
  const emit = defineEmits(['callbackTab']);
  const props = defineProps({
    submitFrom: {
      type: Object,
      default: () => {},
    },
  });

  const salesSceneInfoFromRef = ref<any>('');
  const mainForm = ref<any>({
    account_info: {},
  }); // 表单主体内容
  const selected = ref<any>(''); // 已选数据
  const picArr = ref<Array<any>>([]); //补充材料
  const otherPicArr = ref<Array<any>>([]); // 特殊资质

  const showOssManager = ref<boolean>(false); // oss弹框
  const selectedFormBtnName = ref<string>(''); // 点击图片绑定form
  const picIndex = ref<any>(0); // 存储身份证图片下标，方便赋值
  const selectedSku = ref(); // 选择的sku
  // 选择图片
  const handleClickImg = (val: string, index?: number) => {
    selectedFormBtnName.value = val;
    picIndex.value = index;
    showOssManager.value = true;
  };
  // oss资源改变
  const changOssImage = (val: any) => {
    selectedSku.value = [];
    val.forEach((item: any) => {
      selectedSku.value.push({ url: item.url });
    });
  };
  // oss资源确定
  const handleOss = () => {
    showOssManager.value = false;
    let currentUrl = selectedSku.value[selectedSku.value.length - 1].url; // 当前选择的图片
    if (selectedFormBtnName.value === 'business_addition_pics') {
      // 补充材料
      picArr.value.push({ url: currentUrl });
      mainForm.value.business_addition_pics = picArr.value
        .map((item) => {
          return item.url;
        })
        .join(',');
    } else if (selectedFormBtnName.value === 'qualifications') {
      // 特殊资质图片
      otherPicArr.value.push({ url: currentUrl });
      mainForm.value.qualifications = otherPicArr.value
        .map((item) => {
          return item.url;
        })
        .join(',');
    }
  };
  // 移除文件前触发
  const picArrBeforeRemove: any = (file: any) => {
    return new Promise((resolve, reject) => {
      picArr.value = picArr.value.filter((item) => item.url !== file.url);
      if (typeof mainForm.value.business_addition_pics === 'string') {
        mainForm.value.business_addition_pics = [
          ...mainForm.value.business_addition_pics.split(','),
        ]
          .filter((item) => item !== file.url)
          .join(',');
      } else {
        mainForm.value.business_addition_pics =
          mainForm.value.business_addition_pics
            .filter((item) => item !== file.url)
            .join(',');
      }
      resolve(true);
    });
  };
  const otherPicArrBeforeRemove: any = (file: any) => {
    return new Promise((resolve, reject) => {
      otherPicArr.value = otherPicArr.value.filter(
        (item) => item.url !== file.url
      );
      if (typeof mainForm.value.qualifications === 'string') {
        mainForm.value.qualifications = [
          ...mainForm.value.qualifications.split(','),
        ]
          .filter((item) => item !== file.url)
          .join(',');
      } else {
        mainForm.value.qualifications = mainForm.value.qualifications
          .filter((item) => item !== file.url)
          .join(',');
      }
      resolve(true);
    });
  };

  // 上传失败回调
  const handleError: any = (err: never) => {
    Message.error('上传失败');
  };
  // 上传前校验
  const beforeUpload: any = (file: any) => {
    return new Promise((resolve, reject) => {
      if (
        !fileFormat.value.includes(
          file.name.split('.')[file.name.split('.').length - 1]
        )
      ) {
        reject(new Error('上传失败'));
        Message.error(`请选择 .jpg .jpeg .png .gif .bmp格式文件`);
      } else if (Number((file.size / 1024).toFixed(0)) > 1024) {
        reject(new Error('上传失败'));
        Message.error(`所选文件大小过大，不得超过1M`);
      } else {
        resolve(true);
      }
    });
  };

  const rateSettlementRules = () => {
    window.open('https://kf.qq.com/faq/220228qEfuAz220228bMFji6.html');
  };

  // 上一步/下一步
  const nextStep = (name) => {
    emit('callbackTab', name);
  };

  watch(
    () => props.submitFrom,
    (val) => {
      mainForm.value = val;
      // 补充材料
      if (val.business_addition_pics) {
        let newArr = val.business_addition_pics;
        if (typeof val.business_addition_pics === 'string') {
          newArr = [...val.business_addition_pics.split(',')];
        }
        picArr.value = newArr.map((item) => {
          return { url: item };
        });
      } else {
        mainForm.value.business_addition_pics = '';
      }
      // 特殊资质图片
      if (val.qualifications) {
        let newArr = val.qualifications;
        if (typeof val.qualifications === 'string') {
          newArr = [...val.qualifications.split(',')];
        }
        otherPicArr.value = newArr.map((item) => {
          return { url: item };
        });
      } else {
        mainForm.value.qualifications = '';
      }
    },
    { immediate: true, deep: true }
  );
</script>

<style scoped lang="less">
  :deep(.arco-upload-type-picture-card) {
    display: none;
  }
</style>
